/**
 * 观察者模式
 */

class Subject {
    constructor() {
        this._observers = []
        this._state = 0
    }

    getState() {
        return this._state
    }

    setState(state) {
        this._state = state
        this.notifyAllObservers()
    }

    attach(observer) {
        this._observers.push(observer)
    }

    notifyAllObservers() {
        this._observers.forEach(o => o.on(this._state))
    }
}

class Observer {
    constructor(name, subject) {
        this.name = name
        this.subject = subject
        this.subject.attach(this)
    }

    on(state) {
        console.log(`${this.name}触发了，状态更新为${state}`)
    }
}

function test() {
    const subject = new Subject()
    new Observer('观察者1', subject)
    new Observer('观察者2', subject)
    subject.setState(subject.getState() + 1)
    subject.setState(subject.getState() + 1)
}

console.log('----------------观察者模式-------------------')
test()
